package algorithm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author MaGuangQi
 * @description: 141题,检测一个链表是否有环
 * https://leetcode-cn.com/problems/linked-list-cycle/
 * @date 2020-06-13 22:02
 **/
public class DetermineCycle {
    //解法一. 使用一个数据结构set,存放链表的地址,如果地址重复,说明是有环
    public boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<ListNode>();
        while (head != null) {
            set.add(head);
            if (set.contains(head)) {
                return true;
            }else{
                set.add(head);
            }
            head=head.next;
        }
        return false;
    }
    /**
    *解法三: 使用快慢指针
    */
    public boolean hasCycle3(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        //定义2个指针,一个指针步进2为fast,一个指针步进为1,如果2个指针相等,说明有环
        ListNode slow=head;
        ListNode fast=head.next;
        while (slow!=fast) {
            if (fast == null || fast.next == null) {
                return false;
            } else {
                fast = fast.next.next;
                slow = slow.next;
            }
        }
        return true;
    }
    //解法二: 硬解: 判断链表的next是否为null.如果有空的,说明是没有环,如果没有,说明有环
    //判断空指针
    public boolean hasCycle2(ListNode head) {
        try {
            if (head != null) {
                while (head.next != null) {
                    head=head.next;
                    return true;
                }
            }
        } catch (Exception e) {
            return  false;
        }
        return false;
    }
    private class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }
}
